package com.itheima.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.dto.UserlogInDto;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserlogInVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author :WuJunJie
 * packageName :com.itheima.service.impl
 * fileName :UserServiceImpl
 * creationTime :2022-11-29 9:44
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserlogInVo login(UserlogInDto userlogInDto) {

        User user= getExitInDB(userlogInDto);
        if (user==null){
            return null;
        }
        final String token = JWT.create()
                .setNotBefore(DateUtil.date())
                .setKey("user666".getBytes())
                .sign();
        UserlogInVo userlogInVo = new UserlogInVo();
        BeanUtils.copyProperties(user,userlogInVo);
        userlogInVo.setToken(token);
        return userlogInVo;
    }

    @Override
    public User selectById(String id) {
        User user=userMapper.selectById(id);
        return user;
    }

    @Override
    public Boolean loginout(UserlogInDto userlogInDto) {
        Integer update=userMapper.updateStatus(0,userlogInDto.getId());
        return update>0;
    }


    private User getExitInDB(UserlogInDto userlogInDto) {
        User userInDB=userMapper.selectByPhone(userlogInDto.getPhone());
        if (userInDB==null) {
            User user = new User();
            BeanUtils.copyProperties(userlogInDto, user);
            user.setId(IdUtil.getSnowflakeNextIdStr());
            user.setStatus(1);
            user.setName("小帅");
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setCreateUser(ThreadLocalUtil.getid());
            user.setUpdateUser(ThreadLocalUtil.getid());
            Integer insert=userMapper.insertUser(user);
            if (insert>0){   return user;}
        }
        userInDB.setStatus(1);
        return userInDB;
    }
}
